package cars;

import java.util.HashSet;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;


public class car1 {

	/**
	 * @param args
	 */
	public static void main(String[] args)throws Exception {
		// TODO Auto-generated method stub
		if (args.length!=2) {
			System.err.println("user path err!");
			System.exit(-1);
		}
		Job job=new Job(new Configuration(),"car");
		FileInputFormat.addInputPath(job, new Path(args[0]));
		FileOutputFormat.setOutputPath(job, new Path(args[1]));
		job.setJarByClass(car1.class);
		job.setMapperClass(cMaps.class);
		job.setReducerClass(cReduces.class);
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(Text.class);
		job.waitForCompletion(true);

	}
	public static class cMaps extends Mapper<LongWritable, Text,Text,Text>{
		protected void map(LongWritable key, Text value, org.apache.hadoop.mapreduce.Mapper<LongWritable,Text,Text,Text>.Context context) throws java.io.IOException ,InterruptedException {
			String[] lines = value.toString().split("\t");
			if (lines.length>8 && lines[8]!="" && lines[8]!=null ) {
				String mode=lines[8].trim();//获得车辆类型
				if (lines.length>15 && lines[15]!=null && lines[15]!="") {
					String fule=lines[15].trim();//获得燃料类型
					context.write(new Text(mode),new Text(fule));
				}
			}
		};
	}
	//map输出的中间结果需要经过shuffle阶段处理，
	//处理后的结果：《小型普通客车，『汽油。柴油。。。。』》
	public static class cReduces extends Reducer<Text,Text,Text,Text>{
		protected void reduce(Text k2, java.lang.Iterable<Text> values, org.apache.hadoop.mapreduce.Reducer<Text,Text,Text,Text>.Context context) throws java.io.IOException ,InterruptedException {
			HashSet<String> sets=new HashSet<String>();
			for (Text value:values) {
				sets.add(value.toString());//通过hashset的默认去重功能去重
			}
			context.write(k2,new Text(sets.toString()));
			
		};
	}

}
